package com.bookRecommend.controller;

import com.bookRecommend.commons.ResponseUtils;
import com.bookRecommend.model.User;
import com.bookRecommend.service.IUserService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/user")
@CrossOrigin("*")
public class UserController {
    @Resource
    IUserService userService;

    @RequestMapping
    public ResponseUtils findAll(Integer pageNum, Integer size, String username) {
        PageInfo<User> pageInfo = userService.findPage(pageNum, size, username);
        if (pageInfo != null) {
            return ResponseUtils.success("", pageInfo);
        }
        return ResponseUtils.failure("查找失败！");
    }

    @GetMapping("/login/{username}/{password}")
    public ResponseUtils login(@PathVariable String username,@PathVariable String password) {
        User user = userService.findUserByUsernameAndPassword(username, password);
        if (user != null) {
            return ResponseUtils.success("登录成功", user);
        } else {
            return ResponseUtils.failure("用户名或密码错误!");
        }
    }

    @GetMapping("/{username}")
    public ResponseUtils findUsername(@PathVariable String username) {
        List<User> userList = userService.findUser(username);
        if (userList.size() == 0) {
            return ResponseUtils.success("用户名不存在，可以注册！");
        }
        return ResponseUtils.failure("用户名存在，不可以注册");
    }

    @GetMapping("/{username}/{password}")
    public ResponseUtils verifyOldPass(@PathVariable String username, @PathVariable String password) {
        User user = userService.findUserByUsernameAndPassword(username, password);
        if (user != null) {
            return ResponseUtils.success("密码正确");
        }
        return ResponseUtils.failure("原密码错误");
    }

    @PostMapping("/update/{password}/{id}")
    public ResponseUtils update(@PathVariable String password, @PathVariable Integer id) {
        int flag = userService.updatePassword(password, id);
        if (flag > 0) {
            return ResponseUtils.success("修改成功！");
        }
        return ResponseUtils.failure("修改失败！");
    }

    @RequestMapping("/delete")
    public ResponseUtils delete(Integer id) {
        int i = userService.removeById(id);
        if (i > 0) {
            return ResponseUtils.success("删除成功");
        }
        return ResponseUtils.failure("删除失败");
    }

    @RequestMapping("/register/{username}/{password}/{email}")
    public ResponseUtils register(@PathVariable String username, @PathVariable String password, @PathVariable String email) {
        int flag = userService.addUser(username, password, email);
        if (flag > 0) {
            return ResponseUtils.success("注册成功");
        } else {
            return ResponseUtils.failure("注册失败");
        }
    }
}
